<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 6/20/24
 * Time: 2:14 PM
 */

namespace App\Services;

use OSS\OssClient;
use OSS\Core\OssException;
use Illuminate\Support\Facades\Log;

class OssService
{
    protected $host;
    protected $bucket;
    protected $accessKey;
    protected $secretKey;
    protected $endpoint;


    protected $client;

    protected $fileHost = 'https://ziyi-wechat-gallery.oss-cn-hangzhou.aliyuncs.com';


    /**
     * OssService constructor.
     */
    public function __construct()
    {
        $this->host      = config('oss.host', '');
        $this->bucket    = config('oss.bucket', '');
        $this->accessKey = config('oss.accessKey', '');
        $this->secretKey = config('oss.secretKey', '');
        $this->endpoint  = config('oss.endpoint', '');

        $this->steClient();
    }


    /**
     * 连接OSS
     *
     * @return OssClient
     */
    private function steClient()
    {
        try {
            $this->client = new OssClient($this->accessKey, $this->secretKey, $this->endpoint);
        } catch (\Exception $exception) {
            Log::error('连接OSS失败：' . $exception->getMessage());
        }
    }


    /**
     * 上传文件
     *
     * @param int $bookId
     * @param int $fileKey
     * @param $file
     * @return bool
     */
    public function uploadFile($fileName, $filePath)
    {
        try {
            $this->client->putObject(
                $this->bucket,
                $this->getFilePath($fileName),
                file_get_contents($filePath)
            );

            return $this->fileHost . '/' . $this->getFilePath($fileName);
        } catch (\Exception $exception) {
            Log::error('上传文件失败：' . $exception->getMessage());

            return false;
        }
    }


    /**
     * 删除文件
     *
     * @param int $bookId
     * @param int $fileKey
     * @return bool
     */
    public function deleteFile($fileUrl)
    {
        try {
            $filePath = str_replace($this->fileHost. '/', '', $fileUrl);
            $this->client->deleteObject($this->bucket, $filePath);

            return true;
        } catch (\Exception $exception) {
            Log::error('删除文件失败：' . $exception->getMessage());

            return false;
        }
    }


    /**
     * 获取文件路径
     *
     * @param $fileName
     * @param $fileExt
     * @return string
     */
    public function getFilePath($fileName)
    {
        return date('Ym') . '/' . date('d') . '/' . $fileName;
    }



}
